package cn.mandifal.user.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

import cn.mandifal.mapper.DpUserMapper;
import cn.mandifal.pojo.DpUser;
import cn.mandifal.pojo.DpUserExample;
import cn.mandifal.user.service.UserService;
import cn.mandifal.utils.EmailUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.PageResult;

/**
 * 服务实现层
 * @author shun
 *
 */
@Service(timeout = 3000)
public class UserServiceImpl implements UserService {

	@Autowired
	private DpUserMapper dpUserMapper;
	
	/**
	 * 查询全部
	 */
	@Override
	public List<DpUser> findAll() {
		return dpUserMapper.selectByExample(null);
	}

	/**
	 * 按分页查询
	 */
	@Override
	public PageResult findPage(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);		
		Page<DpUser> page=   (Page<DpUser>) dpUserMapper.selectByExample(null);
		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 通过用户名查找用户
	 * @param username 用户名
	 * @return
	 */
	@Override
	public DpUser findOneUser(String username) {
		return dpUserMapper.selectByUsername(username);
	}

	/**
	 * 增加
	 */
	@Override
	public void add(DpUser user) {
		//注册时间
		user.setCreated(new Date());
		//修改时间
		user.setUpdated(new Date());
		//注册来源
		user.setSourceType("1");
		//密码加密
		user.setPassword( DigestUtils.md5Hex(user.getPassword()));
		dpUserMapper.insert(user);
	}

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private JmsTemplate jmsTemplate;

	@Autowired
	private Destination smsDestination;

	@Override
	public void createSmsCode(final String phone) {
		//1.生成一个6位随机数（验证码）
		final String smsCode=  (long)(Math.random()*1000000)+"";
		System.out.println("验证码："+smsCode);

		//2.将验证码放入redis
		redisTemplate.opsForValue().set(phone,smsCode,300L,TimeUnit.SECONDS);

		//3.将短信内容发送给activeMQ

		jmsTemplate.send(smsDestination, new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				//手机号
				message.setString("mobile", phone);
				//验证码
				message.setString("template_code", "SMS_186579647");
				//签名
				message.setString("sign_name", "车马");
				//param的格式为 code=value，为了格式方便写使用 map来做，不用 map 要这样写，
				//message.setString("param","\"code\"：\"smsCode\"");
				Map map=new HashMap();
				map.put("code", smsCode);
				message.setString("param", JSON.toJSONString(map));
				return message;
			}
		});
	}

	@Override
	public boolean checkSmsCode(String phone, String code) {

		String smsCode= (String) redisTemplate.opsForValue().get(phone);
		if(smsCode==null){
			return false;
		}
		//判断 redis 中的验证码和用户输入的验证码是否一样
		if(!smsCode.equals(code)){
			return false;
		}
		return true;
	}


	/**
	 * 修改
	 */
	@Override
	public void update(DpUser user){
		dpUserMapper.updateByPrimaryKey(user);
	}

	@Override
	public void updatePassword(Map map) {
		String username = (String) map.get("oldUsername");
		//根据用户名得到用户实体
		DpUser dpUser = dpUserMapper.selectByUsername(username);
		String password = (String) map.get("password");
		dpUser.setPassword(DigestUtils.md5Hex(password));
		dpUser.setUsername((String) map.get("username"));
		dpUserMapper.updateByPrimaryKey(dpUser);
	}

	/**
	 *
	 * @param username
	 * @param email
	 * @return
	 */
	@Override
	public DpUser findUserByUsernameAndEmail(String username, String email) {
		DpUserExample example=new DpUserExample();
		DpUserExample.Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		criteria.andEmailEqualTo(email);
		List<DpUser> dpUsers = dpUserMapper.selectByExample(example);
		return dpUsers.get(0);
	}
	/**
	 * 创造验证码并发送
	 * @param email 要发送的邮箱
	 */
	@Override
	public void createCode(String email){
		//得到6 位随机数字
		String code = EmailUtil.achieveCode();
		//存入 redis 以 email 为 key，
		redisTemplate.opsForValue().set(email,code,1800L,TimeUnit.SECONDS);
		//发送邮箱验证码
		EmailUtil.sendAuthCodeEmail(email,code);
	}
	@Override
	public Boolean checkCode(String email,String code){
		String codeFromRedis = (String) redisTemplate.opsForValue().get(email);
		if (codeFromRedis != null){
			if (codeFromRedis.equals(code)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 根据ID获取实体
	 * @param id
	 * @return
	 */
	@Override
	public DpUser findOne(Long id){
		return dpUserMapper.selectByPrimaryKey(id);
	}

	/**
	 * 批量删除
	 */
	@Override
	public void delete(Long[] ids) {
		for(Long id:ids){
			dpUserMapper.deleteByPrimaryKey(id);
		}		
	}
	
	
		@Override
	public PageResult findPage(DpUser user, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		
		DpUserExample example=new DpUserExample();
			DpUserExample.Criteria criteria = example.createCriteria();

			if(user!=null){
						if(user.getUsername()!=null && user.getUsername().length()>0){
				criteria.andUsernameLike("%"+user.getUsername()+"%");
			}
			if(user.getPassword()!=null && user.getPassword().length()>0){
				criteria.andPasswordLike("%"+user.getPassword()+"%");
			}
			if(user.getPhone()!=null && user.getPhone().length()>0){
				criteria.andPhoneLike("%"+user.getPhone()+"%");
			}
			if(user.getEmail()!=null && user.getEmail().length()>0){
				criteria.andEmailLike("%"+user.getEmail()+"%");
			}
			if(user.getSourceType()!=null && user.getSourceType().length()>0){
				criteria.andSourceTypeLike("%"+user.getSourceType()+"%");
			}
			if(user.getNickName()!=null && user.getNickName().length()>0){
				criteria.andNickNameLike("%"+user.getNickName()+"%");
			}
			if(user.getName()!=null && user.getName().length()>0){
				criteria.andNameLike("%"+user.getName()+"%");
			}
			if(user.getStatus()!=null && user.getStatus().length()>0){
				criteria.andStatusLike("%"+user.getStatus()+"%");
			}
			if(user.getHeadPic()!=null && user.getHeadPic().length()>0){
				criteria.andHeadPicLike("%"+user.getHeadPic()+"%");
			}
			if(user.getQq()!=null && user.getQq().length()>0){
				criteria.andQqLike("%"+user.getQq()+"%");
			}
			if(user.getIsMobileCheck()!=null && user.getIsMobileCheck().length()>0){
				criteria.andIsMobileCheckLike("%"+user.getIsMobileCheck()+"%");
			}
			if(user.getIsEmailCheck()!=null && user.getIsEmailCheck().length()>0){
				criteria.andIsEmailCheckLike("%"+user.getIsEmailCheck()+"%");
			}
			if(user.getSex()!=null && user.getSex().length()>0){
				criteria.andSexLike("%"+user.getSex()+"%");
			}
	
		}
		
		Page<DpUser> page= (Page<DpUser>)dpUserMapper.selectByExample(example);
		return new PageResult(page.getTotal(), page.getResult());
	}

}
